package model

import (
	"time"
)

const (
	DateFormat = "2006-01-02"
	TimeFormat = "2006-01-02 15:04:05"
)

type DateTime time.Time

func Now() DateTime {
	return DateTime(time.Now())
}

func (t *DateTime) Unix() int64 {
	return time.Time(*t).Unix()
}

func (t *DateTime) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+TimeFormat+`"`, string(data), time.Local)
	*t = DateTime(now)
	return
}

func (t DateTime) MarshalJSON() ([]byte, error) {
	d := time.Time(t)

	b := make([]byte, 0, len(TimeFormat)+2)
	b = append(b, '"')
	if !d.IsZero() { //0时间处理
		b = d.Local().AppendFormat(b, TimeFormat)
	}
	b = append(b, '"')
	return b, nil
}

func (t DateTime) String() string {
	return time.Time(t).Format(TimeFormat)
}
